import { bindable, containerless } from 'aurelia-framework';

@containerless
export class EmProjectEditStatus {

    @bindable project;
    states = [];

    projectChanged(newValue, oldValue) {
        if (newValue) {
            $.get('admin/task/status/listByProject', {
                pid: this.project.id
            }, (data) => {
                if (data.success) {
                    this.states = data.data;
                } else {
                    toastr.error(data.data);
                }
            });

        }
    }

    addHandler() {
        $.post(`/admin/task/status/create`, {
            pid: this.project.id,
            name: this.name,
            description: this.desc,
        }, (data) => {
            if (data.success) {
                this.states.push(data.data);
                this.name = '';
                this.desc = '';
            } else {
                toastr.error(data.data);
            }
        });
    }

    updateOrder(id, order) {
        $.post(`/admin/task/status/update`, {
            id: id,
            order: order,
        }, (data) => {
            if (data.success) {

            } else {
                toastr.error(data.data);
            }
        });
    }

    upHandler(item) {
        let order = item.order;
        let pre = _.find(this.states, { order: order - 1 });
        if (pre) {
            item.order = pre.order;
            pre.order = order;
            this.states = [...this.states];
            this.updateOrder(item.id, item.order);
            this.updateOrder(pre.id, pre.order);
        }
    }

    downHandler(item) {
        let order = item.order;
        let next = _.find(this.states, { order: order + 1 });
        if (next) {
            item.order = next.order;
            next.order = order;
            this.states = [...this.states];
            this.updateOrder(item.id, item.order);
            this.updateOrder(next.id, next.order);
        }
    }

    delHandler(item) {
        $.post(`/admin/task/status/delete`, {
            id: item.id,
        }, (data) => {
            if (data.success) {
                this.states = _.reject(this.states, { id: item.id });
            } else {
                toastr.error(data.data);
            }
        });
    }

    editNameOkHandler(val, item) {
        $.post(`/admin/task/status/update`, {
            id: item.id,
            name: val,
        }, (data) => {
            if (data.success) {
                toastr.success('更新成功!');
            } else {
                toastr.error(data.data);
            }
        });

    }

    editDescOkHandler(val, item) {
        $.post(`/admin/task/status/update`, {
            id: item.id,
            description: val,
        }, (data) => {
            if (data.success) {
                toastr.success('更新成功!');
            } else {
                toastr.error(data.data);
            }
        });

    }
}
